package com.boruan.qq.zxgylibrary.ui.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.service.manager.GXDrugModule;
import com.boruan.qq.zxgylibrary.service.model.DownOrderBean;
import com.boruan.qq.zxgylibrary.service.model.InsuranceUrl;
import com.boruan.qq.zxgylibrary.service.model.PayInfoResponse;
import com.boruan.qq.zxgylibrary.service.model.SettleDefaultAddressBean;
import com.boruan.qq.zxgylibrary.service.model.ShopCarDataBean;
import com.boruan.qq.zxgylibrary.service.presenter.ConfirmOrderPresenter;
import com.boruan.qq.zxgylibrary.service.view.OrderView;
import com.boruan.qq.zxgylibrary.ui.adapters.GoodsListAdapter;
import com.boruan.qq.zxgylibrary.ui.widgets.DrugPayDialog;
import com.boruan.qq.zxgylibrary.utils.CButtonUtils;
import com.boruan.qq.zxgylibrary.utils.CustomDialogOne;
import com.boruan.qq.zxgylibrary.utils.EventMessage;
import com.boruan.qq.zxgylibrary.utils.PayResult;
import com.chinaums.pppay.unify.UnifyPayListener;
import com.chinaums.pppay.unify.UnifyPayPlugin;
import com.chinaums.pppay.unify.UnifyPayRequest;
import com.convenient.qd.core.base.arouter.ARouterConstant;
import com.convenient.qd.core.base.arouter.ARouterUtils;
import com.convenient.qd.core.bean.BaseResBean;
import com.convenient.qd.core.constant.Constant;
import com.convenient.qd.core.net.BaseHttpObserver;
import com.convenient.qd.core.utils.CommonUtils;
import com.convenient.qd.core.utils.ToastUtils;
import com.convenient.qd.core.utils.UMEventUtil;
import com.convenient.qd.module.user.api.UserModule;
import com.convenient.qd.module.user.widget.PwdInputDialog;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 崔琦 on 2019/8/6.
 * des: 确认订单页面
 */

public class ConfirmOrderActivity extends BaseActivity implements OrderView {

    @BindView(R2.id.rb_rider)
    TextView rbRider;
    @BindView(R2.id.rb_self)
    TextView rbSelf;
    @BindView(R2.id.rg_rider_self)
    LinearLayout rgRiderSelf;
    @BindView(R2.id.tv_money)
    TextView tvMoney;
    @BindView(R2.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R2.id.goods_recycle)
    RecyclerView goodsRecycle;
    @BindView(R2.id.ll_address_info)
    LinearLayout llAddressInfo;
    @BindView(R2.id.tv_prompt_address)
    TextView tvPromptAddress;
    @BindView(R2.id.tv_user_address)
    TextView tvUserAddress;
    @BindView(R2.id.tv_user_info)
    TextView tvUserInfo;
    @BindView(R2.id.tv_input_remark)
    TextView tvInputRemark;
    @BindView(R2.id.tv_delivery_time)
    TextView tvDeliveryTime;
    @BindView(R2.id.rl_delivery_money)
    RelativeLayout rlDeliveryMoney;
    @BindView(R2.id.tv_self_time)
    TextView tvSelfTime;
    @BindView(R2.id.tv_shop_address)
    TextView tvShopAddress;
    @BindView(R2.id.rl_click_address)
    RelativeLayout rlClickAddress;
    @BindView(R2.id.tv_select_invoice)
    TextView tvSelectInvoice;
    @BindView(R2.id.tv_delivery_money)
    TextView tvDeliveryMoney;
    @BindView(R2.id.goods_small_amount)
    TextView goodsSmallAmount;
    @BindView(R2.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R2.id.rl_full_reduce)
    RelativeLayout rlFullReduce;
    @BindView(R2.id.tv_full_reduce_money)
    TextView tvFullReduceMoney;
    @BindView(R2.id.v_line_full_reduce)
    View vLineFullReduce;

    @BindView(R2.id.rl_phone)
    RelativeLayout rl_phone;
    @BindView(R2.id.edt_phone)
    EditText edt_phone;
    @BindView(R2.id.rl_name)
    RelativeLayout rl_name;
    @BindView(R2.id.edt_name)
    EditText edt_name;

    private String payType;
    private GoodsListAdapter goodsListAdapter;
    private boolean isRideOrSelf = true;//判断用户是骑手配送还是到店自取
    private String shopId;
    private ConfirmOrderPresenter confirmOrderPresenter;
    private CustomDialogOne customDialogOne;
    /**
     * 购物车商品费用
     */
    private int shopGoodsMoney;
    /**
     * 需要支付的总的费用
     */
    private double payMoney;
    List<ShopCarDataBean.ResultBean> mShopCarDataBean;

    private int addressId = -1;
    private int deliveryFee;//配送费
    private String fullAddress;//完整地址
    private String userInfo;//用户信息
    private int distance;//距离
    private String shopAddress;//商店地址

    private String tradeId;//下单成功以后返回的交易Id；
    public static int PAY_REQUEST_CODE = 100;//支付返回数据请求码
    public static int PAY_SUCCESS_RESULT_CODE = 101;//支付成功
    public static int PAY_FAILED_RESULT_CODE = 102;//支付失败

    private int fullReducePrice;
    private DrugPayDialog drugPayDialog;
    private Boolean isYBSign = false; // 是否签约医保余额支付
    private Boolean isYBPay; // 是否支持医保余额支付
    private Boolean isPayPwd; // 是否开通支付密码
    private String payPwd; // 支付密码
    private String ybMoney; // 医保余额
    private Boolean isShowYBPay = false; // 是否显示余额支付
    public static int PAY_PWD_REQUEST_CODE = 10000;//支付密码数据请求码
    private PwdInputDialog pwdInputDialog;

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_drug_confirm_order;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ConstantInfo.isCurrentDelete) {
            llAddressInfo.setVisibility(View.GONE);
            tvPromptAddress.setVisibility(View.VISIBLE);
            ConstantInfo.isCurrentDelete = false;
        }

        getInsuranceBalance();
        pwdCheck();
    }

    // 是否开通支付密码
    private void pwdCheck() {
        UserModule.getInstance().pwdCheck(new BaseHttpObserver<BaseResBean<Boolean>>() {
            @Override
            public void onSuccess(BaseResBean<Boolean> resBean) {
                if (null != resBean) {
                    if (resBean.getResult()) {
                        //已经有密码
                        isPayPwd = true;
                    } else {
                        //没有密码
                        isPayPwd = false;
                    }
                }
            }

            @Override
            public void onFailure(int status, String msg) {
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //用户可能不支付而点击返回键返回，在这里获取一下订单状态进入订单详情
        if (ConstantInfo.weChatPayBack) {
            confirmOrderPresenter.getOrderDetailInfo(tradeId);
            ConstantInfo.weChatPayBack = false;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        registerEvent();
        if (getIntent() != null) {
            shopId = getIntent().getStringExtra("shopId");
        }

        pwdInputDialog = new PwdInputDialog(this);
        payType = "";
        customDialogOne = new CustomDialogOne(this, R.style.CustomDialogOne);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        goodsRecycle.setLayoutManager(manager);
        goodsListAdapter = new GoodsListAdapter(this);
        goodsRecycle.setAdapter(goodsListAdapter);

        confirmOrderPresenter = new ConfirmOrderPresenter(this);
        confirmOrderPresenter.onCreate();
        confirmOrderPresenter.attachView(this);

        /** 获取默认地址 */
        confirmOrderPresenter.getDefaultAddress(shopId);
        /** 获取购物车列表数据 */
        confirmOrderPresenter.getShopCarData(shopId, addressId);
    }

    private void getInsuranceBalance() {
        if (TextUtils.isEmpty(ConstantInfo.ybBalance) || ConstantInfo.ybBalance.equals("-1")) {
            isYBSign = false;
        } else {
            isYBSign = true;
            ybMoney = ConstantInfo.ybBalance;
        }
        GXDrugModule.getInstance().getInsuranceBalance(new BaseHttpObserver<BaseResBean<InsuranceUrl>>() {
            @Override
            public void onSuccess(BaseResBean<InsuranceUrl> res) {
                if (res.getResult().getContent().equals("-1")) {
                    isYBSign = false;
                } else {
                    ybMoney = res.getResult().getContent();
                    isYBSign = true;
                }
                ConstantInfo.ybBalance = res.getResult().getContent();
            }

            @Override
            public void onFailure(int status, String msg) {
                isYBSign = false;
                ConstantInfo.ybBalance = "";
            }
        });
    }

    private void orderSubmit() {
        int deliveryType;
        String remark = tvInputRemark.getText().toString();
        if (isRideOrSelf) {
            deliveryType = 1;//骑手配送
            if (llAddressInfo.getVisibility() == View.GONE) {
                promptSelectAddress();
            } else if (mShopCarDataBean == null || mShopCarDataBean.size() == 0) {
                Toast.makeText(this, "您还没有选择药品！", Toast.LENGTH_SHORT).show();
            } else {
                confirmOrderPresenter.userDownOrder(0, deliveryType, distance, deliveryFee, addressId, shopGoodsMoney + deliveryFee - fullReducePrice, shopId, mShopCarDataBean, remark,"","");
            }
        } else {
            deliveryType = 2;
            if(TextUtils.isEmpty(edt_phone.getText().toString())){
                Toast.makeText(this, "请输入取货人手机号", Toast.LENGTH_SHORT).show();
                return;
            }
            if(!CommonUtils.isChinaPhoneLegal(edt_phone.getText().toString())){
                Toast.makeText(this, "请输入正确的取货人手机号", Toast.LENGTH_SHORT).show();
                return;
            }

            if(TextUtils.isEmpty(edt_name.getText().toString())){
                Toast.makeText(this, "请输入取货人姓名", Toast.LENGTH_SHORT).show();
                return;
            }

            if (mShopCarDataBean == null || mShopCarDataBean.size() == 0) {
                Toast.makeText(this, "您还没有选择药品！", Toast.LENGTH_SHORT).show();
            } else {
                confirmOrderPresenter.userDownOrder(0, deliveryType, 0, 0, 0, shopGoodsMoney - fullReducePrice, shopId, mShopCarDataBean, remark,
                        edt_phone.getText().toString(),edt_name.getText().toString());
            }
        }
    }

    @OnClick({R2.id.iv_back, R2.id.tv_commit_order, R2.id.tv_select_invoice, R2.id.rb_rider, R2.id.rb_self, R2.id.rl_click_address, R2.id.tv_delivery_time, R2.id.rl_pay_type, R2.id.tv_input_remark})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();

        } else if (i == R.id.tv_commit_order) {
            UMEventUtil.onOrderEventObject(this, "2001007", Constant.sceneId);
            if (!CButtonUtils.isFastDoubleClick(R.id.tv_commit_order)) {
                if (isRideOrSelf && addressId <= 0) {
                    ToastUtils.showShort("请选择收货地址");
                    return;
                }
                if (TextUtils.isEmpty(payType)) {
                    ToastUtils.showShort("请选择支付方式");
                    return;
                }

                if (isPayPwd == null) {
                    ToastUtils.showShort("信息异常请重新下单");
                    finish();
                    return;
                }
                if (payType.equals("YBPAY") && !isPayPwd) {
                    ARouterUtils.navigation(ARouterConstant.ACTIVITY_USER_PWD_SHIREN_ACTIVITY);
                    return;
                }
                if (payType.equals("YBPAY")) {
                    // 跳转输入支付密码界面
                    showPwdDialog();
                } else {
                    orderSubmit();
                }


            } else {
                Toast.makeText(this, "请不要过快点击！", Toast.LENGTH_SHORT).show();
            }


        } else if (i == R.id.rb_rider) {
//            if(isSupportYBPay){
            drugPayDialog = null;
            payType = "";
            tvPayType.setTextColor(Color.parseColor("#757575"));
            tvPayType.setText("请选择");
//            }


            int mPayMoney = shopGoodsMoney + deliveryFee - fullReducePrice;
            double f1 = (double) mPayMoney / 100;
            BigDecimal b = new BigDecimal(f1);
            payMoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            goodsSmallAmount.setText("" + payMoney);
            tvMoney.setText("￥" + payMoney);

            isRideOrSelf = true;
            rbRider.setBackgroundResource(R.drawable.drug_shape_confirm_order_true);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) rbRider.getLayoutParams();
            layoutParams.height = getPxFromDp(45);
            rbRider.setLayoutParams(layoutParams);

            rbSelf.setBackgroundResource(R.drawable.drug_shape_confirm_order_false);
            LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) rbSelf.getLayoutParams();
            layoutParams1.height = getPxFromDp(40);
            rbSelf.setLayoutParams(layoutParams1);

            rlClickAddress.setVisibility(View.VISIBLE);
            rlDeliveryMoney.setVisibility(View.VISIBLE);
            tvSelfTime.setText("立即送出");
            tvShopAddress.setVisibility(View.GONE);
            tvDeliveryTime.setText("约20:01送达");
            rl_name.setVisibility(View.GONE);
            rl_phone.setVisibility(View.GONE);

        } else if (i == R.id.rb_self) {
//            if(isSupportYBPay){
            drugPayDialog = null;
            payType = "";
            tvPayType.setTextColor(Color.parseColor("#757575"));
            tvPayType.setText("请选择");
//            }

            double f2 = (double) (shopGoodsMoney - fullReducePrice) / 100;
            BigDecimal b1 = new BigDecimal(f2);
            payMoney = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            goodsSmallAmount.setText("" + payMoney);
            tvMoney.setText("￥" + payMoney);

            isRideOrSelf = false;
            rbRider.setBackgroundResource(R.drawable.drug_shape_confirm_order_false);
            LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) rbRider.getLayoutParams();
            layoutParams2.height = getPxFromDp(40);
            rbRider.setLayoutParams(layoutParams2);

            rbSelf.setBackgroundResource(R.drawable.drug_shape_confirm_order_true);
            LinearLayout.LayoutParams layoutParams3 = (LinearLayout.LayoutParams) rbSelf.getLayoutParams();
            layoutParams3.height = getPxFromDp(45);
            rbSelf.setLayoutParams(layoutParams3);

            rlClickAddress.setVisibility(View.GONE);
            rlDeliveryMoney.setVisibility(View.GONE);
            tvSelfTime.setText("自取时间");
            tvShopAddress.setVisibility(View.VISIBLE);
            tvDeliveryTime.setText("早8:00-晚9:00");
            rl_name.setVisibility(View.VISIBLE);
            rl_phone.setVisibility(View.VISIBLE);

        } else if (i == R.id.rl_click_address) {
            Intent intent = new Intent(ConfirmOrderActivity.this, AddressListActivity.class);
            intent.putExtra("shopId", shopId);
            startActivityForResult(intent, 10);

        } else if (i == R.id.tv_delivery_time) {//selectDeliveryTime();

        } else if (i == R.id.rl_pay_type) {
            if (!isYBSign) {
                GXDrugModule.getInstance().getInsuranceBalance(new BaseHttpObserver<BaseResBean<InsuranceUrl>>() {
                    @Override
                    public void onSuccess(BaseResBean<InsuranceUrl> res) {
                        if (res.getResult().getContent().equals("-1")) {
                            isYBSign = false;
                        } else {
                            ybMoney = res.getResult().getContent();
                            isYBSign = true;
                        }

                    }

                    @Override
                    public void onFailure(int status, String msg) {
                        isYBSign = false;
                    }
                });
            }

            selectPayType();

        } else if (i == R.id.tv_input_remark) {
            Intent intent1 = new Intent(ConfirmOrderActivity.this, OrderRemarkActivity.class);
            startActivityForResult(intent1, 10);

        } else if (i == R.id.tv_select_invoice) {
//            Intent intent2 = new Intent(ConfirmOrderActivity.this, SelectInvoiceActivity.class);
//            startActivityForResult(intent2, 10);

        }
    }

    public void promptSelectAddress() {
        final PopupWindow addressWindow = new PopupWindow();
        View convertView = LayoutInflater.from(this).inflate(R.layout.drug_pop_prompt_address, null);
        Button btn_know = (Button) convertView.findViewById(R.id.btn_know);

        addressWindow.setContentView(convertView);
        btn_know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addressWindow.dismiss();
                Intent intent = new Intent(ConfirmOrderActivity.this, AddressListActivity.class);
                intent.putExtra("shopId", shopId);
                startActivityForResult(intent, 10);
            }
        });
        addressWindow.setWidth(ConstantInfo.screenWidth - getPxFromDp(80));
        addressWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        addressWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        addressWindow.setTouchable(true);
        addressWindow.setOutsideTouchable(true);
        /** 设置popupWindow动画 */
        addressWindow.setAnimationStyle(R.style.style_down_to_up_animation);
        //不设置焦点的话点击外面dismiss的同时会响应外层的触摸事件
        backgroundAlpha(0.3f);
        addressWindow.setFocusable(false);
        addressWindow.showAtLocation(findViewById(R.id.rl_confirm), Gravity.CENTER, 0, 0);
        addressWindow.setOnDismissListener(new poponDismissListener());
    }

    Boolean isSupportYBPay = false;

    public void selectPayType() {
        String des = "";
        if (isYBPay == null) {
            ToastUtils.showShort("信息异常请重新下单");
            finish();
            return;
        }

        if (isRideOrSelf && addressId <= 0) {
            ToastUtils.showShort("请选择收货地址");
            return;
        }

        Boolean isOpenYBPay = isYBPay;
        if (isOpenYBPay) {
            if (isRideOrSelf && deliveryFee > 0) {
                // 线上购买
                isOpenYBPay = false;
                des = "配送费不为0，暂不支持医保余额支付";
            }
        } else {
            des = "本商户未开通医保余额支付，暂不支持";
        }
        Long money = 0L;
        if (isYBSign) {
            int mPayMoney = shopGoodsMoney + deliveryFee - fullReducePrice;
            if (TextUtils.isEmpty(ybMoney) || Long.valueOf(ybMoney) <= 0) {
                isOpenYBPay = false;
                ybMoney = "0";
                des = "医保余额不足";
            }
            money = Long.valueOf(ybMoney);
            if (money < mPayMoney) {
                isOpenYBPay = false;
                ybMoney = "0";
                des = "医保余额不足";
            }
        }
//        if(isYBSign && isOpenYBPay){
//            isSupportYBPay = true;
//        }else {
//            isSupportYBPay = false;
//        }

        if (drugPayDialog == null) {
            drugPayDialog = new DrugPayDialog(this, money, isYBSign, isOpenYBPay, des);
            drugPayDialog.setPayPwd(isPayPwd);
            drugPayDialog.setShowYBPay(isShowYBPay);
        } else {
            drugPayDialog.setDes(des);
            drugPayDialog.setMoney(money);
            drugPayDialog.setYBPay(isOpenYBPay);
            drugPayDialog.setYBSign(isYBSign);
            drugPayDialog.setPayPwd(isPayPwd);
            drugPayDialog.setPayType(payType);
            drugPayDialog.setShowYBPay(isShowYBPay);
            drugPayDialog.setState();
        }


        drugPayDialog.show();
        drugPayDialog.setOnPayClickListener(new DrugPayDialog.OnPayClickListener() {
            @Override
            public void onClickPay(String type, String payText) {
                payType = type;
                tvPayType.setTextColor(Color.parseColor("#2f71fb"));
                tvPayType.setText(payText);
            }
        });

    }


    /**
     * 得到dp转化成的px
     */
    public int getPxFromDp(float dip) {
        float result = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
        return (int) result;
    }

    /**
     * PopupWindow背景变暗
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void showProgress() {
        customDialogOne.show();
    }

    @Override
    public void hideProgress() {
        customDialogOne.dismiss();
    }

    @Override
    public void getDefaultAddressSuccess(SettleDefaultAddressBean.ResultBean settleDefaultAddressBean) {
        if (settleDefaultAddressBean != null) {
            try {
                if (settleDefaultAddressBean.getFulladdress().contains(settleDefaultAddressBean.getAddress())) {
                    //老地址，让用户自己去选择
                    llAddressInfo.setVisibility(View.GONE);
                    tvPromptAddress.setVisibility(View.VISIBLE);
                } else {
                    llAddressInfo.setVisibility(View.VISIBLE);
                    tvPromptAddress.setVisibility(View.GONE);

                    addressId = settleDefaultAddressBean.getId();
                    ConstantInfo.mAddressId = addressId;
                    distance = settleDefaultAddressBean.getDistance();

                    tvUserAddress.setText(settleDefaultAddressBean.getFulladdress());
                    tvUserInfo.setText(settleDefaultAddressBean.getContactperson() + settleDefaultAddressBean.getContactphone());
                    /** 获取购物车列表数据 */
                    confirmOrderPresenter.getShopCarData(shopId, addressId);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("error", e.getMessage());
            }

        } else {
            addressId = 0;
            confirmOrderPresenter.getShopCarData(shopId, addressId);
            llAddressInfo.setVisibility(View.GONE);
            tvPromptAddress.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getDefaultAddressFailed(String msg) {
        llAddressInfo.setVisibility(View.GONE);
        tvPromptAddress.setVisibility(View.VISIBLE);
        addressId = 0;
        confirmOrderPresenter.getShopCarData(shopId, addressId);
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getShopCarDataSuccess(List<ShopCarDataBean.ResultBean> shopCarDataBean) {
        if (shopCarDataBean.size() == 0) {
            ToastUtils.showShort("暂无商品信息");
            finish();
            return;
        }

        mShopCarDataBean = shopCarDataBean;

        /** 新增满减优惠逻辑 */
        fullReducePrice = shopCarDataBean.get(0).getFullReducePrice();
        if (fullReducePrice == 0) {//不显示满减
            rlFullReduce.setVisibility(View.GONE);
            vLineFullReduce.setVisibility(View.GONE);
        } else {
            rlFullReduce.setVisibility(View.VISIBLE);
            vLineFullReduce.setVisibility(View.VISIBLE);

            double f1 = (double) fullReducePrice / 100;
            BigDecimal b = new BigDecimal(f1);
            double showMoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            tvFullReduceMoney.setText("-￥" + showMoney);
        }


        shopAddress = shopCarDataBean.get(0).getShopAddress();
        tvShopAddress.setText(shopAddress);
        tvShopName.setText(shopCarDataBean.get(0).getShopName());
        goodsListAdapter.setData(shopCarDataBean.get(0).getShopCartSkuDTOList());

        shopGoodsMoney = shopCarDataBean.get(0).getTotalPrice();
        deliveryFee = shopCarDataBean.get(0).getDeliveryFee();
        double f = (double) deliveryFee / 100;
        BigDecimal b1 = new BigDecimal(f);
        double deliveryMoney = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvDeliveryMoney.setText("￥" + deliveryMoney);

        int mPayMoney = shopGoodsMoney + deliveryFee - fullReducePrice;
        double f1 = (double) mPayMoney / 100;
        BigDecimal b = new BigDecimal(f1);
        payMoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        goodsSmallAmount.setText("" + payMoney);
        tvMoney.setText("￥" + payMoney);
        isYBPay = shopCarDataBean.get(0).getMedicalPayFlag() == 1 ? true : false;
        isShowYBPay = shopCarDataBean.get(0).getShowMedicalPayFlag() == 0 ? false : true;
    }

    @Override
    public void getShopCarDataFailed(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void userDownOrderSuccess(final DownOrderBean.ResultBean orderBean) {
//        Toast.makeText(this, "下单成功", Toast.LENGTH_SHORT).show();
        tradeId = orderBean.getOrderId();
        confirmOrderPresenter.getPayParam(orderBean.getOrderId(), payType, payPwd);
    }

    private void showPwdDialog() {
        pwdInputDialog = new PwdInputDialog(this);
        pwdInputDialog.show();
        pwdInputDialog.setOnPwdValidateListener(new PwdInputDialog.onPwdValidateListener() {
            @Override
            public void onPwdValidateSuccess(String pwd) {
                payPwd = pwd;
                orderSubmit();
//                confirmOrderPresenter.getPayParam(tradeId,payType,pwd);
            }

            @Override
            public void onCloseClick() {
//                confirmOrderPresenter.getOrderDetailInfo(tradeId);
            }
        });
    }

    @Override
    public void userDownOrderFailed(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void userPayNoticeSuccess(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void userPayNoticeFailed(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getPayParamsSuccess(PayInfoResponse.ResultBean dataBean) {
        if (payType.equals("ALIPAY_PSCAN")) {
            Uri uri = Uri.parse(dataBean.getUrl());
            String payUrl = uri.getQueryParameter("imageUrl");
            Intent intent = new Intent(ConfirmOrderActivity.this, GYAlipayWebActivity.class);
            intent.putExtra("url", payUrl);
            intent.putExtra("tradeId", tradeId);
            startActivityForResult(intent, PAY_REQUEST_CODE);

        } else if (payType.equals("WXPAY_APP")) {//微信

            /*
             * 获取综合支付SDK对象
             * 参数：Context
             * */
            UnifyPayPlugin payPlugin = UnifyPayPlugin.getInstance(this);

            /*
             * 新建统一支付请求类
             *  */
            UnifyPayRequest payRequest = new UnifyPayRequest();

            /*
             * 初始化支付渠道(如：微信支付)
             * */
            payRequest.payChannel = UnifyPayRequest.CHANNEL_WEIXIN;
            /*
             * 设置下单接口中返回的数据(appRequestData)
             * */
            payRequest.payData = dataBean.getUrl();

            payPlugin.setListener(new UnifyPayListener() {
                @Override
                public void onResult(String resultCode, String resultInfo) {
                    if (resultCode.equals("0000")) {
                        //支付成功
                        UMEventUtil.onOrderEventObject(ConfirmOrderActivity.this, "2001009", Constant.sceneId);
                        Toast.makeText(ConfirmOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        //其他
                        UMEventUtil.onOrderEventObject(ConfirmOrderActivity.this, "2001010", Constant.sceneId);
                        Toast.makeText(ConfirmOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    //别管支付成功还是失败，都调订单详情接口获取状态，跳转到对应的订单详情
                    if (ConstantInfo.weChatPayBack) {
                        confirmOrderPresenter.getOrderDetailInfo(tradeId);
                        ConstantInfo.weChatPayBack = false;
                    }
                }
            });
            //开始支付
            payPlugin.sendPayRequest(payRequest);
            ConstantInfo.weChatPayBack = true;//表示调了统一下单接口，前往微信支付
        } else if (payType.equals("YBPAY")) { // 医保
            confirmOrderPresenter.getOrderDetailInfo(tradeId);
        } else if (payType.equals("CLOUDPAY")) {//
            String tn = dataBean.getUrl();
            if(!TextUtils.isEmpty(tn)){
                Log.i("xxxx",tn);
                UPPayAssistEx.startPay(ConfirmOrderActivity.this, null, null, tn, "00");
            }
        }
    }

    @Override
    public void getPayParamsFailed(String msg) {
        ToastUtils.showShort(msg);
        setResult(122);
        finish();
    }

    @Override
    public void getOrderDetailSuccess(int orderStatus) {
        Intent intent = new Intent(ConfirmOrderActivity.this, OrderDetailActivity.class);
        if (orderStatus == 21 || orderStatus == 30) {//这里支付异常的状态，正常传订单状态
            intent.putExtra("orderStatus", orderStatus + "");
        } else {
            intent.putExtra("orderStatus", "99");//支付成功以后状态变为99，支付完成，为了适配骑手配送和到店自取
        }
        intent.putExtra("orderId", tradeId);
        startActivity(intent);
        setResult(122);
        finish();
    }

    @Override
    public void getOrderDetailFailed(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            backgroundAlpha(1f);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(ConfirmOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                //支付成功关掉本页刷新购物车商品数量
                /** 支付成功调接口改变状态 */
                //changePayState();
                setResult(11);
                ConfirmOrderActivity.this.finish();

            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(ConfirmOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == 13) {
            addressId = data.getIntExtra("addressId", 0);
            ConstantInfo.mAddressId = addressId;
            if (addressId == 0 || addressId == -1) {
                confirmOrderPresenter.getDefaultAddress(shopId);
                return;
            }
            llAddressInfo.setVisibility(View.VISIBLE);
            tvPromptAddress.setVisibility(View.GONE);
            ConstantInfo.mAddressId = addressId;
//            deliveryFee = data.getIntExtra("deliveryFee",0);
            fullAddress = data.getStringExtra("fullAddress");
            userInfo = data.getStringExtra("userInfo");
            distance = data.getIntExtra("distance", 0);

            tvUserAddress.setText(fullAddress);
            tvUserInfo.setText(userInfo);
            confirmOrderPresenter.getShopCarData(shopId, addressId);
//            /** 先把配送费转换成元 */
//            double f = (double)deliveryFee / 100;
//            BigDecimal b1 = new BigDecimal(f);
//            double deliveryMoney = b1.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//            tvDeliveryMoney.setText("￥" + deliveryMoney);
//
//            /** 因为配送费改变会涉及到计算总计 */
//            int mPayMoney = shopGoodsMoney + deliveryFee - fullReducePrice;
//            double f1 = (double) mPayMoney / 100;
//            BigDecimal b = new BigDecimal(f1);
//            payMoney = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//            goodsSmallAmount.setText("" + payMoney);
//            tvMoney.setText("￥" + payMoney);

        } else if (requestCode == 10 && resultCode == 14) {
            String remark = data.getStringExtra("remark");
            tvInputRemark.setText(remark);
        } else if (requestCode == 10 && resultCode == 15) {
            String invoice = data.getStringExtra("invoice");
            tvSelectInvoice.setText(invoice);
        } else if (requestCode == PAY_REQUEST_CODE && resultCode == PAY_SUCCESS_RESULT_CODE) {
            //confirmOrderPresenter.userPayNotice(tradeId,"WXPay");
            int orderStatus = data.getIntExtra("orderStatus", 0);
            Toast.makeText(ConfirmOrderActivity.this, "支付成功！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(ConfirmOrderActivity.this, OrderDetailActivity.class);
            intent.putExtra("orderStatus", "99");//支付成功以后状态变为99，支付完成，为了适配骑手配送和到店自取
            intent.putExtra("orderId", tradeId);
            startActivity(intent);
            setResult(122);
            finish();
        } else if (requestCode == PAY_REQUEST_CODE && resultCode == PAY_FAILED_RESULT_CODE) {
            int orderStatus = data.getIntExtra("orderStatus", 0);
            Intent intent = new Intent(ConfirmOrderActivity.this, OrderDetailActivity.class);
            intent.putExtra("orderStatus", orderStatus + "");
            intent.putExtra("orderId", tradeId);
            startActivity(intent);
            setResult(122);
            finish();
        } else if (requestCode == PAY_PWD_REQUEST_CODE) {
//            payPwd = data.getStringExtra("payPwd");
//            confirmOrderPresenter.getPayParam(tradeId,payType,payPwd);
        } else if(payType.equals("CLOUDPAY")){
            if (data == null) {
                return;
            }

            String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
            String str = data.getExtras().getString("pay_result");
            if (str.equalsIgnoreCase("success")) {
                msg = "支付成功！";
                confirmOrderPresenter.getOrderDetailInfo(tradeId);
            } else if (str.equalsIgnoreCase("fail")) {
                msg = "支付失败！";
            } else if (str.equalsIgnoreCase("cancel")) {
                msg = "用户取消了支付";
            }
            confirmOrderPresenter.getOrderDetailInfo(tradeId);
            ToastUtils.showShortCenter(msg);
        }
    }

    protected void registerEvent() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    protected void unRegisterEvent() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage message) {
        if (message.getState() == EventMessage.EventState.WECHAT_PAY_SUCCESS) {
            Toast.makeText(ConfirmOrderActivity.this, "支付成功！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(ConfirmOrderActivity.this, OrderDetailActivity.class);
            intent.putExtra("orderStatus", "2");
            intent.putExtra("orderId", tradeId);
            startActivity(intent);
            setResult(122);
            finish();
        } else if (message.getState() == EventMessage.EventState.WECHAT_PAY_ERROR) {
            Intent intent = new Intent(ConfirmOrderActivity.this, PayCheckStandActivity.class);
            intent.putExtra("payFailed", "failed");
            intent.putExtra("orderId", tradeId);
            intent.putExtra("money", String.valueOf(payMoney));
            intent.putExtra("shopName", mShopCarDataBean.get(0).getShopName());
            startActivity(intent);
            setResult(122);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterEvent();
    }
}
